from django.http import JsonResponse
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
from rest_framework.response import Response
from management.initialization import DataInitializer
from management.models import UserControl
from management.tasks import UserDataTasks
from management.updater import DataUpdater
from rest_framework_simplejwt.authentication import JWTAuthentication

from utils.logging_utils import log_request_response


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def initialize_user_data_view(request):
    try:
        result = DataInitializer.initialize_user_data(request.user)
        return JsonResponse({
            'message': 'User data initialized successfully.',
            'result': result  # 可选，根据实际情况返回方法执行的具体结果
        }, status=200)
    except Exception as e:
        return JsonResponse({
            'error': str(e)
        }, status=500)


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def update_user_data(request):
    try:
        DataUpdater.update_data_fetch(request.user)
        return JsonResponse({'message': 'Data update initiated successfully.'}, status=200)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def frontend_initialize_user_data(request):
    user_id = request.user.id  # 获取当前认证用户的ID
    UserDataTasks.async_initialize_user_data.delay(user_id)  # 调用异步任务

    return Response({"message": "User data initialization task has been submitted."}, status=200)


@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
@log_request_response
def frontend_get_computing_status(request):
    try:
        # 获取当前用户的 UserControl 实例
        user_control = UserControl.objects.get(user=request.user)
        # 返回 is_computing 状态
        return Response({"is_computing": user_control.is_computing}, status=200)
    except UserControl.DoesNotExist:
        # 如果用户没有 UserControl 实例，返回错误信息
        return Response({"error": "User control data not found."}, status=404)
